/********************* INCLUDE *****************************/

/********************* PARAMETRE *****************************/
/* Input Output parameter */
int key0InputPin=0;
int key1InputPin=1;
int DoorSensorInputPin=2;
int MotorStartedInputPin=3;
int PetrolPompRelayOutputPin=4;

/* Delay Parameter */
int DelayToInputCodeInSecond=5;
int DelayBeforeSecurityGoesOnInSecond=30;

/********************* VARIABLE *****************************/
long firstKeyPressedAtTime=0;
long doorOpenAtTime=0;
long motorStartedAtTime=0;
boolean key0HasBeenPressed=false;
boolean key1HasBeenPressed=false;
//etape represent the combinaison step
//etape==0 -> key 0 has been pressed
//etape==1 -> key 0 and then key 1 have been pressed
//etape==2 -> key 0, 1 and then 0 have been pressed, combination have been entered successfully 
int etape=0;
boolean combinationCodeAsBeenInputed=false;


/********************* Setup *****************************/
void setup(){
  pinMode(PetrolPompRelayOutputPin, OUTPUT);
  digitalWrite(PetrolPompRelayOutputPin, LOW); 
  doorOpenAtTime=millis(); 

}

/********************* Loop *****************************/
void loop(){
  startTime=millis();
  if( analogRead(key0InputPin)==255 ){
    key0HasBeenPressed=true;
    key1HasBeenPressed=false;
  }
  else if( analogRead(key1InputPin)==255 ){
    key1HasBeenPressed=true;
    key0HasBeenPressed=false;
  }
  else
  {
    key0HasBeenPressed=false;
    key1HasBeenPressed=false;
  }
  if( key0HasBeenPressed||key1HasBeenPressed )
  {
    if ( firstKeyPressedAtTime+5000 < millis() ){
      firstKeyPressedAtTime=0;
      etape=0;
    }
    else if( (firstKeyPressedAtTime==0) || ( (firstKeyPressedAtTime+5000) > millis() ) )
    {
      if(key0HasBeenPressed)
        firstKeyPressedAtTime=millis();    
      switch(etape){
        case 0:
        {
          if(key0HasBeenPressed)
            etape=1;
        }
        case 1:
        {
          if(key1HasBeenPressed)
            etape=2;
        }
        case 2:
        {
          if(key0HasBeenPressed)
            combinationCodeAsBeenInputed=true;
        }
      }//switch end 
    }//time ==0 or in the 5 second   
  }//key 0 or 1 has been presed


if( analogRead(DoorSensorInputPin)==255 ){
  combinationCodeAsBeenInputed=false;
  doorOpenAtTime=millis();
}
if( analogRead(MotorStartedInputPin)==255 && motorStartedAtTime==0 )
  motorStartedAtTime=millis();
else
  motorStartedAtTime=0;

if( combinationCodeAsBeenInputed || motorStartedAtTime==0 )
  digitalWrite(PetrolPompRelayOutputPin, HIGH); 
else if( ((motorStartedAtTime+DelayBeforeSecurityGoesOnInSecond*1000)<millis()) && motorStartedAtTime!=0 )
  digitalWrite(PetrolPompRelayOutputPin, LOW);  

}

